<template>
  <div class="resources pd30 flex flexjcsb">
    <div class="menuLeft grow">
      <div class="panelWrap">
        <div class="title flex flexac flexjcsb fs14 cfff fwb pl p-r-20">
          <div>系统菜单</div>
        </div>

        <div class="comp-tree">
          <el-tree
            ref="tree"
            class="tree-grow m-t-10"
            :data="setTree"
            :props="defaultProps"
            :expand-on-click-node="true"
            :default-expanded-keys="[1, 105, 107, 106, 167, 177, 216, 218]"
            highlight-current
            :node-key="NODE_KEY"
            @node-click="handleNodeClick"
          >
            <div slot-scope="{ node, data }" class="comp-tr-node">
              <!-- 编辑状态 -->
              <template v-if="node.isEdit">
                <el-input :ref="'slotTreeInput' + data[NODE_KEY]" v-model="data.name" class="xiugxi21321" autofocus size="mini" @blur.stop="handleInput(node, data)" @keyup.enter.native="handleInput(node, data)" />
              </template>
              <!-- 非编辑状态 -->
              <template v-else>
                <!-- 名称： 新增节点增加class（is-new） -->
                <span :class="[data[NODE_KEY] < NODE_ID_START ? 'is-new' : '', 'comp-tr-node--name']">
                  {{ node.label }}
                </span>
              </template>
            </div>
          </el-tree>
        </div>
      </div>
    </div>
    <div class="panelWrap menuCon">
      <div class="title flex flexac flexjcsb fs14 cfff fwb pl p-r-20">
        <div>系统平台权限资源管理</div>
      </div>
      <div class="con">
        <div class="con-row flex flexac pl search-box">
          <div class="inputLable inputLable2 flex flexac">
            <el-select v-model="value" placeholder="请选择系统平台" @change="handleSystem">
              <el-option
                v-for="item in systemList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </div>
          <!-- <div class="groupbtn flex m-l-60 ">
            <div class="selectBtn flex flexac " @click="getResourcesList">查询</div>
            <el-button class="emptyBtn flexcenter m-l-25" type="info" @click="handleEmptySearch"><i class="iconfont icon-qingkong" />清空</el-button>
          </div> -->
        </div>
        <div class="con-row flex flexac flexjcsb pl">
          <el-button class="defaultbtn" type="primary" @click="handleRefresh"><i class="el-icon-refresh" :class="refresh?'goRefresh':''" />刷 新</el-button>
          <div class="m-r-25 flex">
            <el-button class="defaultbtn" type="primary" @click="handleAdd"><i class="el-icon-circle-plus-outline" />添加</el-button>
            <el-button class="defaultbtn" type="primary" @click="handleExportExcel"><i class="iconfont icon-wenjiandaochu" />导出</el-button>
            <div class="pre m-l-10">
              <el-button class="defaultbtn pre" type="primary" @click="handleSenior('field')"><i class="iconfont icon-shezhi" />字段
              </el-button>
              <div class="selectUl" :class="seniorSet.field?'showSelectUl':'hideSelectUl'">
                <div v-for="(item,i) in tablehead" :key="i" class="li">
                  <el-checkbox v-model="item.isShow">{{ item.label }}</el-checkbox>
                </div>
              </div>
            </div>
            <div class="pre m-l-10">
              <el-button class="defaultbtn" type="primary" @click="handleSenior('sortable')"><i class="iconfont icon-shezhi" />排序</el-button>
              <div class="selectUl" :class="seniorSet.sortable ? 'showSelectUl' : 'hideSelectUl'">
                <div v-for="(item,i) in tablehead" v-if="item.isShow" :key="i" class="li">
                  <el-checkbox v-model="item.sortable">{{ item.label }}</el-checkbox>
                </div>
              </div>
            </div>
            <!-- <el-button class="defaultbtn" @click="handleExportExcel" type="primary"><i class="iconfont icon-shezhi"></i>固定</el-button> -->
          </div>
        </div>

        <el-table
          id="dataList"
          ref="dataList"
          class="con-table"
          type="expand"
          :data="dataList.slice((paging.currentPage - 1) * paging.pageSize, paging.currentPage * paging.pageSize)"
          highlight-current-row
        >
          <!-- <el-table-column width="90" type="selection" label="全选" /> -->

          <template v-for="item in tablehead">
            <el-table-column v-if="item.isShow" :key="item.index" :width="item.width" align="center" :sortable="item.sortable" :show-overflow-tooltip="true" :prop="item.prop" :label="item.label" />
          </template>

          <!-- <el-table-column label="系统ID" align="center" width="80">
            <template slot-scope="scope">
              <span>{{ scope.row.sysId }}</span>
            </template>
          </el-table-column> -->

          <!-- <el-table-column align="center" label="资源图标">
            <template slot-scope="scope">
              <el-image class="logo" :src="scope.row.iconUrl" lazy>
                <div slot="error" class="image-slot">
                  <el-image class="errorImg" :src="url" lazy fit="fill" />
                </div>
              </el-image>
            </template>
          </el-table-column> -->

          <el-table-column align="center" width="200" label="资源链接url">
            <template slot-scope="scope">
              <!-- <el-link type="primary" :href="scope.row.url" target="_blank">{{ scope.row.url }}</el-link> -->
              <el-link type="primary">{{ scope.row.url }}</el-link>
            </template>
          </el-table-column>

          <el-table-column label="资源类型" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.resourceType ? '菜单' : '操作' }}</span>
            </template>
          </el-table-column>

          <el-table-column label="资源顺序" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.sort }}</span>
            </template>
          </el-table-column>

          <el-table-column label="资源权限" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.displayType === 1 ? '可用' : scope.row.displayType === 2 ? '不可用' : '可用' }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="name" width="200px" align="center" label="基本操作">
            <template slot-scope="scope">
              <el-button class="defaultbtn" type="primary" plain @click="handleEdit(scope.$index, scope.row)">
                <i class="el-icon-edit" />编辑</el-button>
              <el-button slot="reference" class="defaultbtn" type="danger" plain @click="handleDeleteBtn(scope.$index, scope.row)">
                <i class="el-icon-delete" />删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination class="paginationWrap flex " :current-page="paging.currentPage" :page-sizes="paging.pageSizeArr" :page-size="paging.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="paging.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>

    <ResourcesEdit v-model="visible" class="addMenuDialog" :data="editResources" :is-edit="isEdit" @handleRefresh="handleRefresh" @handleCloseDialog="handleCloseDialog" />

  </div>
</template>

<script>
import ResourcesEdit from './dialog'
import { findPlatforms } from '@/api/baseInfo/authority/resources'
import { findMenuDetail, deleteMenu, findMenuList } from '@/api/baseInfo/authority/menu'
import { showNotice, formatDateTime, transData } from '@/utils/toolclass'
// import storage from '@/utils/storage'

export default {
  components: {
    ResourcesEdit
  },
  props: {},
  data() {
    return {
      sysId: '',
      systemList: [],
      value: '',
      paging: {
        currentPage: 1,
        pageSize: 10,
        pageSizeArr: [10, 20, 50, 100],
        total: 0
      },
      tablehead: [
        {
          index: 0,
          prop: 'parentId',
          label: '父资源ID',
          width: '100',
          sortable: false,
          fixed: true,
          isShow: true
        },
        {
          index: 1,
          prop: 'id',
          label: '资源ID',
          sortable: false,
          width: '80',
          fixed: true,
          isShow: true
        },
        {
          index: 2,
          prop: 'name',
          label: '资源名称',
          width: '140',
          sortable: false,
          fixed: true,
          isShow: true
        }
      ],
      dataList: [],
      param: {
        id: 2,
        name: ''
      },
      visible: false,
      editResources: {},
      isEdit: false,
      refresh: false,
      url: require('@/assets/error.png'),
      seniorSet: {
        'field': false,
        'sortable': false
      },
      setTree: [], // tree数据
      NODE_KEY: 'id', // id对应字段
      MAX_LEVEL: 3, // 设定最大层级
      NODE_ID_START: 0, // 新增节点id，逐次递减
      startId: null,
      defaultProps: {// 默认设置
        children: 'children',
        label: 'name'
      },
      initParam: {// 新增参数
        name: '新增节点',
        parentId: 1
        // children: []
      },
      currentNode: {},
      routeArr: [],
      parentArr: [],
      parentId: '',
      parentName: '',
      version: null
    }
  },
  created() {
    this.getResourcesList()
    this.getSystem()
    this.startId = this.NODE_ID_START
  },
  mounted() {
    this.$storage.set('upUrl', JSON.stringify({ 'path': '/authority/resources' }))
  },
  methods: {
    // 获取平台
    getSystem() {
      findPlatforms().then(res => {
        // console.log(res)
        if (res.code === '000000') {
          this.systemList = res.data
        } else {
          // showNotice('error', '提示', res.msg)
        }
      })
    },
    // 根据平台获取菜单
    handleSystem(val) {
      // console.log(val, this.value)
      findMenuList('', this.param.name, this.paging.currentPage, 100, val).then(res => {
        // console.log(res)
        if (res.code === '000000') {
          this.parentArr = res
          this.dataList = res.data
          const i = res.data.map(item => item)
          this.paging.total = i.length
          this.setTree = transData(res.data, 'id', 'parentId')
        }
      })
      this.getResourcesList()
    },
    // 删除菜单
    handleDeleteBtn(index, row) {
      this.$alert('这个操作会删除和它相关联的所有数据,确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showCancelButton: true,
        callback: action => {
          if (action === 'confirm') {
            this.handleDelete(row.id)
          }
        }
      })
    },
    handleDelete(id) {
      deleteMenu(id).then(res => {
        if (res.code === '000000') {
          showNotice('success', '提示', '删除成功')
          this.handleRefresh()
          this.getUserList()
        }
      })
    },
    handlRoleCancel(index, row) {
      // console.log(index, row)
    },
    // getSelctSystem(val) {
    //   console.log(1111)

    //   findPlatforms(val).then(res => {
    //     this.dataList = res.data
    //     const i = this.dataList.map(item => item)
    //     this.paging.total = i.length
    //   })
    // },
    getMenuDetail(id) {
      // console.log(id)
      this.dataList = []
      findMenuDetail(id).then((res) => {
        // console.log(res)
        if (res.code === '000000') {
          this.dataList.push(res.data)
          const i = this.dataList.map(item => item)
          this.paging.total = i.length
        }
      })
    },
    handleNodeClick(res) {
      this.currentNode = res
      // console.log(res)
      this.getMenuDetail(res.id)
    },
    handleInput(_node, _data) { // 修改节点
      console.log('修改节点')
      console.log(_node, _data)
      // 退出编辑状态
      if (_node.isEdit) {
        this.$set(_node, 'isEdit', false)
        console.log('_node------')
        console.log(_node)
      }
    },
    handleSenior(type) {
      if (type === 'field') {
        this.seniorSet.field = !this.seniorSet.field
      }
      if (type === 'sortable') {
        this.seniorSet.sortable = !this.seniorSet.sortable
      }
    },

    handleExportExcel() {
      require.ensure([], () => {
        const { export_json_to_excel } = require('@/excel/Export2Excel')
        const tHeader = ['父资源ID', '资源ID', '资源名称', '资源链接', '资源类型', '资源顺序', '资源权限']
        const filterVal = ['parentId', 'id', 'name', 'url', 'resourceType', 'sort', 'displayType']
        const data = this.formatJson(filterVal, this.dataList)
        export_json_to_excel(tHeader, data, '系统平台权限资源表(' + formatDateTime().ymd) + ')'
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    handleRefresh() {
      this.refresh = true
      if (this.value !== '') {
        // console.log(this.value)
        this.handleSystem(this.value)
      }
      setTimeout(() => {
        this.refresh = false
      }, 1200)
    },
    getResourcesList() {
      findPlatforms().then((res) => {
        if (res.code === '000000') {
          // console.log(res)
          // this.dataList = res.data
          res.data.forEach(val => {
            this.sysId = val.id
            return this.sysId
          })
          // const i = res.data.map(item => item)
          // this.paging.total = i.length
          // this.setTree = transData(res.data, 'resourceId', 'parentId')
        }
      })
    },
    handleEmptySearch() {
      this.param.id = ''
      this.param.name = ''
      this.getResourcesList()
    },
    handleEdit(index, row) {
      this.parentArr.data.filter(item => {
        if (item.id === row.parentId) {
          this.parentName = item.name
          return this.parentName
        }
      })
      const data = this.systemList.filter(item => {
        if (item.id === this.value) {
          // console.log(item)
          return item.name
        }
      })
      this.visible = true
      this.isEdit = true
      this.sysId = row.id
      // console.log(row)
      this.editResources = {
        displayType: row.displayType === null ? 1 : row.displayType, // 显示类型（1：可用且可显示；2：可显示但不可用；）
        id: row.id, // ID
        name: row.name, // 菜单名称
        parentId: row.parentId, // 父级ID
        parentName: this.parentName, // 父级名称
        sort: row.sort, // 排序号
        sysId: this.value, // 平台ID
        sysName: data[0].name, // 平台名称
        url: row.url, // 系统URL
        version: row.version, // 版本号
        resourceType: '菜单'
      }
    },
    handleAdd() {
      // console.log(this.value)
      if (this.value === '') {
        showNotice('warning', '提示', '请选择平台')
        return
      }
      if (this.currentNode.parentId === undefined) {
        showNotice('warning', '提示', '请选择左侧菜单')
        return
      }
      this.visible = true
      this.isEdit = false
      this.parentId = null
      this.parentName = ''
      if (this.parentArr.code === '000000') {
        this.parentArr.data.filter(item => {
          // console.log(item)
          if (item.parentId === this.parentId) {
            this.parentName = item.name
            return this.parentName
          }
        })
        // console.log(this.parentName)
        this.parentArr.data.filter(item => {
          if (item.id === this.currentNode.parentId) {
            return this.currentNode
          }
        })
      }
      const data = this.systemList.filter(item => { if (item.id === this.value) return item.name })
      this.editResources = {
        displayType: 1, // 显示类型（1：可用且可显示；2：可显示但不可用；）
        id: 0, // ID
        name: '', // 菜单名称
        parentId: this.currentNode.id === undefined ? this.parentId : this.currentNode.id, // 父级ID
        parentName: this.currentNode.name === undefined ? this.parentName : this.currentNode.name, // 父级名称
        sort: '', // 排序号
        sysId: this.value, // 平台ID
        sysName: data[0].name, // 平台名称
        url: '', // 系统URL
        version: 1, // 版本号
        resourceType: '菜单'
      }
    },
    handleCloseDialog() {
      this.visible = !this.visible
    },
    handleSizeChange(val) {
      this.paging.pageSize = val
      this.getResourcesList()
    },
    handleCurrentChange(val) {
      this.paging.currentPage = val
      this.getResourcesList()
    }
  }
}
</script>
<style lang="scss">
@import "@/styles/public.scss";
.resources {
  .errorImg {
  display: inline-block;
  width: 60px;
  height: 60px;
}
.el-table td, .el-table th {
  padding: 9px 0;
}
.menuLeft {
  margin-right: 20px;
  .panelWrap {
    height: 100%;
  }
}
.menuCon {
  width: 80%;
}

.show-btns {
  opacity: 1;
}

/* common end */

.comp-tree {
  width: 100%;
  max-width: 700px;
  max-height: 80vh;
  padding: 10px;
  overflow: auto;
  // 顶部按钮
  .comp-tr-top {
    width: 100px;
    margin-bottom: 2em;
  }
  // 自定义节点
  .comp-tr-node {
    // label
    .comp-tr-node--name {
      display: inline-block;
      line-height: 40px;
      min-height: 40px;
      // 新增
      &.is-new {
        // font-weight: bold;
      }
    }
    // button
    .comp-tr-node--btns {
      margin-left: 10px;
      opacity: 0;
      transition: opacity 0.1s;
      .el-button {
        transform: scale(0.8); // 缩小按钮
        & + .el-button {
          margin-left: -1px;
        }
      }
    }
  }
  // 高亮显示按钮
  .is-current {
    & > .el-tree-node__content {
      .comp-tr-node--btns {
        @extend .show-btns;
      }
    }
  }
  // 悬浮显示按钮
  .el-tree-node__content {
    &:hover {
      .comp-tr-node--btns {
        @extend .show-btns;
      }
    }
  }
}

.deleteBtn {
  margin-left: 5px !important;
}
.operationBtn {
  .defaultbtn {
    margin-left: 5px;
  }
}
}
</style>
